package com.ekuaitu.kuaitu.fragment;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.media.WantuService;
import com.alibaba.sdk.android.media.upload.UploadListener;
import com.alibaba.sdk.android.media.upload.UploadTask;
import com.alibaba.sdk.android.media.utils.FailReason;
import com.ekuaitu.kuaitu.R;
import com.ekuaitu.kuaitu.activity.MainActivity;
import com.ekuaitu.kuaitu.api.ApiStore;
import com.ekuaitu.kuaitu.api.UrlConstant;
import com.ekuaitu.kuaitu.bean.CommitCertificateBean;
import com.ekuaitu.kuaitu.bean.UploadImageBean;
import com.ekuaitu.kuaitu.utils.Constants;
import com.ekuaitu.kuaitu.utils.DriveDialog;
import com.ekuaitu.kuaitu.utils.ImageLoader;
import com.ekuaitu.kuaitu.utils.KuaituDialog;
import com.ekuaitu.kuaitu.utils.MyApplication;
import com.ekuaitu.kuaitu.utils.SDCardUtils;
import com.ekuaitu.kuaitu.utils.SharedPreferencesKey;
import com.ekuaitu.kuaitu.utils.SharedPreferencesUtils;

import com.ekuaitu.kuaitu.utils.Toast.ToastCompat;
import com.michael.selectimage.PhotoPickerActivity;
import com.umeng.analytics.MobclickAgent;
import com.zhy.autolayout.AutoLinearLayout;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * A simple {@link Fragment} subclass.
 */
public class LisenceFragment extends Fragment implements UploadListener {

    @BindView(R.id.progressBar_drive_commit)
    AutoLinearLayout progressBarDriveCommit;
    @BindView(R.id.drive_iv_idcard_front)
    ImageView driveIvIdcardFront;
    @BindView(R.id.drive_iv_idcard_rear)
    ImageView driveIvIdcardRear;
    @BindView(R.id.drive_next_step)
    TextView driveNextStep;
    @BindView(R.id.drive_ll_idcard)
    AutoLinearLayout driveLlIdcard;
    @BindView(R.id.drive_iv_drive)
    ImageView driveIvDrive;
    @BindView(R.id.drive_commit)
    TextView driveCommit;
    @BindView(R.id.drive_ll_ivDrive)
    AutoLinearLayout driveLlIvDrive;
    private Context mContext;
    private String[] picTokenArray = new String[]{"", "", ""};
    private String[] picKeyArray = new String[]{"", "", ""};
    private WantuService wantuService;
    private int submitType;
    private UploadListener mListener = this;
    private LisenceFragment fragment = this;

    public LisenceFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getContext();
        WantuService.enableHttpDNS();
        WantuService.enableLog();
        wantuService = WantuService.getInstance();
        wantuService.asyncInit(mContext);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_certify_driving, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }

    private void confirmDriveCommit() {
        progressBarDriveCommit.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).confirmDrivingCommit(MyApplication.getInstance().getRequestFieldMap(),picKeyArray[0], picKeyArray[1], picKeyArray[2]).enqueue(new Callback<CommitCertificateBean>() {
            @Override
            public void onResponse(Call<CommitCertificateBean> call, Response<CommitCertificateBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        progressBarDriveCommit.setVisibility(View.GONE);
                        final DriveDialog selfDialog = new DriveDialog(mContext);
                        selfDialog.setTitle("");
                        selfDialog.setMessage("恭喜您证照认证信息已提交成功!");
                        selfDialog.setYesOnclickListener("确定", new DriveDialog.onYesOnclickListener() {
                            @Override
                            public void onYesClick() {
                                SharedPreferencesUtils.getInstance(mContext).putIntValue(SharedPreferencesKey.USER_TRIP_METHOD, 1);
                                startActivity(new Intent(mContext, MainActivity.class));
                                selfDialog.dismiss();
                            }
                        });
                        selfDialog.setNoOnclickListener("", new DriveDialog.onNoOnclickListener() {
                            @Override
                            public void onNoClick() {
                                selfDialog.dismiss();
                            }
                        });
                        selfDialog.show();
                    } else {
                        progressBarDriveCommit.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    progressBarDriveCommit.setVisibility(View.GONE);
                    ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<CommitCertificateBean> call, Throwable t) {
                progressBarDriveCommit.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void uploadImage(final File picFile) {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).uploadImage(MyApplication.getInstance().getRequestFieldMap(),"jpg", "", "", "", "1", "0", "kuaitu"
        ).enqueue(new Callback<UploadImageBean>() {
            @Override
            public void onResponse(Call<UploadImageBean> call, Response<UploadImageBean> response) {

                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        picTokenArray[submitType] = response.body().getAttachment().getToken();
                        picKeyArray[submitType] = response.body().getAttachment().getKey();
                        wantuService.upload(picFile, mListener, picTokenArray[submitType]);
                    } else {
                        progressBarDriveCommit.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    progressBarDriveCommit.setVisibility(View.GONE);
                    ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();

                }
            }

            @Override
            public void onFailure(Call<UploadImageBean> call, Throwable t) {
                progressBarDriveCommit.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onUploading(UploadTask uploadTask) {

    }

    @Override
    public void onUploadFailed(UploadTask uploadTask, FailReason failReason) {
        Message message = new Message();
        message.arg1 = 5;
        Bundle b = new Bundle();
        b.putString("failReason", failReason.getMessage());
        message.setData(b);
        handler.sendMessage(message);

    }

    @Override
    public void onUploadComplete(UploadTask uploadTask) {
        Message message = new Message();
        message.arg1 = 4;
        Bundle b = new Bundle();
        message.setData(b);
        handler.sendMessage(message);
    }

    @Override
    public void onUploadCancelled(UploadTask uploadTask) {
        Message message = new Message();
        message.arg1 = 6;
        Bundle b = new Bundle();
        message.setData(b);
        handler.sendMessage(message);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.arg1) {
                case 1:
                    progressBarDriveCommit.setVisibility(View.VISIBLE);
                    break;
                case 2:
                    //成功压缩
                    String pathName = msg.getData().getString("compressPath");
                    pics.add(pathName);
                    //上传图片
                    compressFile = new File(pathName);
                    uploadImage(compressFile);
                    break;
                case 3:
                    //压缩失败
                    progressBarDriveCommit.setVisibility(View.GONE);
                    picKeyArray[submitType] = "";
                    ToastCompat.makeText(mContext, "图片压缩失败，请重试", Toast.LENGTH_LONG).show();
                    break;
                case 4: //上传成功
                    progressBarDriveCommit.setVisibility(View.GONE);
                    if (submitType == 0) {
                        ImageLoader.getInstance().displayImage(mContext, compressFile, driveIvIdcardFront);
                    } else if (submitType == 1) {
                        ImageLoader.getInstance().displayImage(mContext, compressFile, driveIvIdcardRear);
                    } else if (submitType == 2) {
                        ImageLoader.getInstance().displayImage(mContext, compressFile, driveIvDrive);
                    }
                    break;
                case 5:
                    //上传失败
                    progressBarDriveCommit.setVisibility(View.GONE);
                    picKeyArray[submitType] = "";
                    ToastCompat.makeText(mContext, msg.getData().getString("failReason"), Toast.LENGTH_SHORT).show();
                    break;
                case 6:
                    //上传取消
                    progressBarDriveCommit.setVisibility(View.GONE);
                    picKeyArray[submitType] = "";
                    ToastCompat.makeText(mContext, "图片上传取消", Toast.LENGTH_SHORT).show();
                    break;
            }
            super.handleMessage(msg);
        }
    };


    @OnClick({R.id.drive_iv_drive, R.id.drive_iv_idcard_rear, R.id.drive_iv_idcard_front, R.id.drive_next_step, R.id.drive_commit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.drive_iv_idcard_front:
                final KuaituDialog kuaituDialog = new KuaituDialog(getContext());
                kuaituDialog.setTitle(getString(R.string.dialogTitle));
                kuaituDialog.setMessage("注意：需要上传本人手持身份证照片，须看清脸部五官以及身份证件编号。");
                kuaituDialog.setYesOnclickListener("确定", new KuaituDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        submitType = 0;
                        //跳转图片选择
                        Intent intent = new Intent(mContext, PhotoPickerActivity.class);
                        intent.putExtra(PhotoPickerActivity.EXTRA_SHOW_CAMERA, true);
                        intent.putExtra(PhotoPickerActivity.EXTRA_SELECT_MODE, PhotoPickerActivity.MODE_SINGLE);
                        intent.putExtra(PhotoPickerActivity.EXTRA_CROP_IMAGE, false);
                        startActivityForResult(intent, submitType);
                        kuaituDialog.dismiss();
                    }
                });
                kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        kuaituDialog.dismiss();
                    }
                });
                kuaituDialog.show();
                break;
            case R.id.drive_iv_idcard_rear: {
                submitType = 1;
                Intent intent = new Intent(mContext, PhotoPickerActivity.class);
                intent.putExtra(PhotoPickerActivity.EXTRA_SHOW_CAMERA, true);
                intent.putExtra(PhotoPickerActivity.EXTRA_SELECT_MODE, PhotoPickerActivity.MODE_SINGLE);
                intent.putExtra(PhotoPickerActivity.EXTRA_CROP_IMAGE, false);
                startActivityForResult(intent, submitType);
                break;
            }
            case R.id.drive_next_step:
                MobclickAgent.onEvent(this.getActivity(), Constants.LICENSE_VERIFICATION);
                if (picKeyArray[0].equals("") || picKeyArray[1].equals("")) {
                    ToastCompat.makeText(mContext, getString(R.string.uploadIdCard), Toast.LENGTH_LONG).show();
                } else {
                    driveLlIdcard.setVisibility(View.GONE);
                    driveLlIvDrive.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.drive_iv_drive: {
                submitType = 2;
                Intent intent = new Intent(mContext, PhotoPickerActivity.class);
                intent.putExtra(PhotoPickerActivity.EXTRA_SHOW_CAMERA, true);
                intent.putExtra(PhotoPickerActivity.EXTRA_SELECT_MODE, PhotoPickerActivity.MODE_SINGLE);
                intent.putExtra(PhotoPickerActivity.EXTRA_CROP_IMAGE, false);
                startActivityForResult(intent, submitType);
                break;
            }
            case R.id.drive_commit:
                MobclickAgent.onEvent(this.getActivity(), Constants.LICENSE_VERIFICATION);
                if (picKeyArray[2].equals("")) {
                    ToastCompat.makeText(mContext, getString(R.string.uploadDriverLicense), Toast.LENGTH_LONG).show();
                } else {
                    confirmDriveCommit();
                    break;
                }
                break;
        }
    }

    private File originalFile;
    private File compressFile;
    private ArrayList<String> pics = new ArrayList<>();


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == submitType) {   //获得图片后
            if (resultCode == Activity.RESULT_OK) {
                final ArrayList<String> result = data.getStringArrayListExtra(PhotoPickerActivity.KEY_RESULT);
                if (result == null || result.size() == 0) {
                    return;
                }
                originalFile = new File(result.get(0));
                Luban.with(mContext)
                        .load(originalFile)  //传入要压缩的图片
                        .setCompressListener(new OnCompressListener() {
                            @Override
                            public void onStart() {
                                Message message = new Message();
                                message.arg1 = 1;
                                Bundle b = new Bundle();
                                b.putString("originalPath", result.get(0));
                                message.setData(b);
                                handler.sendMessage(message);
                            }

                            @Override
                            public void onSuccess(File file) {
                                Message message = new Message();
                                message.arg1 = 2;
                                Bundle b = new Bundle();
                                b.putString("compressPath", file.getAbsolutePath());
                                message.setData(b);
                                handler.sendMessage(message);
                            }

                            @Override
                            public void onError(Throwable e) {
                                Message message = new Message();
                                message.arg1 = 3;
                                handler.sendMessage(message);
                            }
                        }).launch();    //启动压缩

            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (pics != null && pics.size() != 0) {
            for (int i = 0; i < pics.size(); i++) {
                SDCardUtils.removeFileFromSDCard(pics.get(i));
            }
        }
    }
}
